package com.shujia.kafka

import java.util.Properties

import org.apache.kafka.clients.producer.{KafkaProducer, ProducerRecord}

object Demo4Trans {
  def main(args: Array[String]): Unit = {

    /**
      * 1、创建生产者
      *
      */

    val properties = new Properties

    //1、指定kafkabroker地址
    properties.setProperty("bootstrap.servers", "master:9092")

    //指定事务编号
    properties.setProperty("transactional.id", "asdasd")

    //2、指定kv的序列化类
    properties.setProperty("key.serializer", "org.apache.kafka.common.serialization.StringSerializer")
    properties.setProperty("value.serializer", "org.apache.kafka.common.serialization.StringSerializer")

    //生产者对象
    val producer = new KafkaProducer[String, String](properties)

    //初始化事务
    producer.initTransactions()

    //开启事务
    producer.beginTransaction()


    //发送数据到kafka
    //事务没有提交的时候实际上数据已经在kafka中了，数据在kafka中是一个未提交的状态
    producer.send(new ProducerRecord[String, String]("words", "java"))

    Thread.sleep(5000)

    producer.send(new ProducerRecord[String, String]("words", "spark"))

    //提交事务
    //在提交事务的时候数据的状态转换成已提交
    producer.commitTransaction()

    /**
      *
      * --isolation-level read_committed :  只读已提交数据，默认可以读未提交数据
      *
      * kafka-console-consumer.sh --bootstrap-server  master:9092 --from-beginning --isolation-level read_committed --topic words
      */
    //关闭链接
    producer.close()
  }

}
